package com.jacklei.ch15;

import sun.rmi.runtime.Log;

import java.util.HashMap;
import java.util.Map;

/*
* 给定一个二叉树的根节点 root ，和一个整数 targetSum ，求该二叉树里节点值之和等于 targetSum 的 路径 的数目。

路径 不需要从根节点开始，也不需要在叶子节点结束，但是路径方向必须是向下的（只能从父节点到子节点）。

 

示例 1：



输入：root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
输出：3
解释：和等于 8 的路径有 3 条，如图所示。
示例 2：

输入：root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出：3
 

提示:

二叉树的节点个数的范围是 [0,1000]
-109 <= Node.val <= 109 
-1000 <= targetSum <= 1000 

来源：力扣（LeetCode）
链接：https://leetcode.cn/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。*/
public class PathSumIII {
    public static void main(String[] args) {
        PathSumIII p = new PathSumIII();
        TreeNode treeNode = new TreeNode(10);
        treeNode.left = new TreeNode(5);
        treeNode.left.left = new TreeNode(3);

        treeNode.left.left.left = new TreeNode(3);
        treeNode.left.left.right = new TreeNode(-2);

        treeNode.left.right = new TreeNode(2);
        treeNode.left.right.right = new TreeNode(1);

        treeNode.right = new TreeNode(-3);
        treeNode.right.right = new TreeNode(11);
        System.out.println(p.pathSum(treeNode, 8));
    }
    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) return 0;

        int ret = rootSum(root, targetSum);

        ret += pathSum(root.left,targetSum);
        ret += pathSum(root.right,targetSum);
        return ret;

    }

    private int rootSum(TreeNode root, int targetSum) {
        int res = 0;

        if(root == null){
            return 0;
        }
        int val = root.val;
        if(val == targetSum) {
            res++;
        }
        res += rootSum(root.left,targetSum - val);
        res += rootSum(root.right, targetSum-val);
        return res;
    }

    //前缀和
    public int pathSum2(TreeNode root,int targetSum){
        Map<Long,Integer> prefix = new HashMap<>();
        prefix.put(0L,1);
        return dfs(root, prefix, 0L, targetSum);
    }

    private int dfs(TreeNode root, Map<Long, Integer> prefix, long curr, int targetSum) {
        if (root == null) return 0;
        int res = 0;
        curr += root.val;
        res = prefix.getOrDefault(curr - targetSum,0);//产看前缀和中是否有 符合要求的；
        prefix.put(curr,prefix.getOrDefault(curr,0)+1);//把当前的值计算 并存进前缀和中；
        res += dfs(root.left,prefix,curr,targetSum);
        res += dfs(root.right,prefix,curr,targetSum);
        prefix.put(curr,prefix.getOrDefault(curr,0)-1); //遍历完此节点删除 记录；
        return  res;
    }

}
